function IEVersion() {
  var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串  
  var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器  
  var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器  
  var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
  if (isIE) {
    var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
    reIE.test(userAgent);
    var fIEVersion = parseFloat(RegExp["$1"]);
    if (fIEVersion == 7) {
      return 7;
    } else if (fIEVersion == 8) {
      return 8;
    } else if (fIEVersion == 9) {
      return 9;
    } else if (fIEVersion == 10) {
      return 10;
    } else {
      return 6; //IE版本<=7
    }
  } else if (isEdge) {
    return 'edge'; //edge
  } else if (isIE11) {
    return 11; //IE11  
  } else {
    return -1; //不是ie浏览器
  }
}
const isIe = () => {
  const ieVersion = IEVersion()
  return ieVersion !== -1
}
const isMobile = videojs.browser.IS_IOS || videojs.browser.IS_ANDROID
const API_BASE_URL = 'http://221.6.15.201:9199'
const APP_NAME = "test";
const SALT = "test1234567890";


new Vue({
  el: '#app',
  data: {
    players: [],
    playerLength: 4,
    playerIdx: 0,
    dialogTableVisible: false,
    dialogCodeVisible: false,
    deviceList: [],
    currentDevices: [],
    total: 0,
    currentPage: 1,
    pageSize: 10,
    listLoading: false,
    deviceSearchName: '',
    //当前正在操作的格子
    currentPlayer: null,
    deviceStatus: 1,
    deviceStatusArr: [
      { value: -1, label: '所有' },
      { value: 0, label: '离线' },
      { value: 1, label: '在线' }
    ]
  },
  computed: {
    playerBtnGroup() {
      var list = [{
        num: 1,
        name: "单屏"
      }, {
        num: 4,
        name: "四分屏"
      }, {
        num: 9,
        name: "九分屏"
      }];

      if (!isIe() && !isMobile) {
        list.push({
          num: 16,
          name: "十六分屏"
        })
      }
      return list;
    },
  },
  watch: {
    playerLength: function(val) {
      this.setPlayerLength(val)
    },
    deviceSearchName(val) {
      this.currentPage = 1
      const devices = this.getDevicesByName(val)
      this.handleAllList(devices)
    },
    deviceStatus(val) {
      this.currentPage = 1
      const devices = this.getDevicesByStatus(val)
      this.handleAllList(devices)
    }
  },
  methods: {
    isIE() {
      return !!videojs.browser.IE_VERSION;
    },
    flvSupported() {
      return videojs.browser.IE_VERSION || (flvjs.getFeatureList() && flvjs.getFeatureList().mseLiveFlvPlayback);
    },
    rtcSupported() {
      return !!window.RTCPeerConnection;
    },
    setPlayerLength(len) {
      if (len == this.players.length) {
        return
      }
      this.clearVideos()
      this.players = []
      this.playerLength = len
      this.loadedData = false;
      this.playerIdx = 0;
      for (var i = 0; i < len; i++) {
        this.players.push({
          index: i,
          serial: "",
          code: "",
          url: "",
          protocol: "",
          poster: "",
          bLoading: false,
          bCloseShow: false,
          bControls: false,
          bSmart: false,
          bFullscreen: false,
          closeTimer: 0
        })
      }
    },
    clearVideos() {
      for (var idx in this.players) {
        this.closeVideo(idx);
      }
    },
    closeVideo(idx) {
      var player = this.players[idx];
      if (!player) {
        return;
      }
      if (player.closeTimer) {
        clearTimeout(player.closeTimer);
        player.closeTimer = 0;
      }
      player.bCloseShow = false;
      player.bControls = false;
      player.bLoading = false;
      player.bSmart = false;
      player.bFullscreen = false;
      player.poster = "";
      player.url = "";
      player.ptzType = 0;
      player.serial = "";
      player.code = "";
    },
    beforeDialog() {
      this.deviceList = []
      this.currentDevices = []
      this.total = 0
      this.currentPage = 1
    },
    selectChannel(index, player) {
      this.dialogTableVisible = true
      this.currentPlayer = player
      this.getIpcLit()
    },
    resetCloseTimer(player) {
      player.bCloseShow = true;
      player.bControls = true;
      if (player.closeTimer) {
        clearTimeout(player.closeTimer)
      }
      player.closeTimer = setTimeout(() => {
        player.bCloseShow = false;
        player.bControls = false;
      }, 2000);
    },
    getIpcLit() {
      const that = this
      this.listLoading = true
      $.ajax({
        type: "GET",
        url: API_BASE_URL + "/if/getdevicelist?appname=test&token=" + hex_md5(APP_NAME + SALT),
        success: function(result) {
          that.listLoading = false
          result = $.parseJSON(result)
          if (result['devices']) {
            that.tempList = result['devices']
            that.handleAllList(that.getDevicesByStatus(that.deviceStatus))
          }
        },
        fail: function(err) {
          that.listLoading = false
          that.$message.error('获取设备列表失败')
        }
      });
    },
    handleAllList(list) {
      this.deviceList = list
      this.total = this.deviceList.length
      this.getCurrentDevices(this.currentPage)
    },
    getCurrentDevices(page) {
      const start = (page - 1) * this.pageSize
      const end = start + this.pageSize
      this.currentDevices = this.deviceList.slice(start, end)
    },
    handleCurrentChange(val) {
      this.getCurrentDevices(val)
    },
    getDevicesByName(name) {
      let list = []
      const regx = new RegExp(`${name}`)
      list = this.tempList.filter(function(device) {
        if (device['name'] && device['name'].search(regx) !== -1) {
          return true
        }
      })
      return list
    },
    getDevicesByStatus(status) {
      let list = []
      if (status === -1) {
        return this.tempList
      }
      list = this.tempList.filter(function(device) {
        return device['online'] === status
      })
      return list
    },
    deviceRowClick(row) {
      if (row['online'] === 1) {
        this.getChoosedDeviceUrl(row)
      } else {
        this.$message.error('离线设备不能播放')
      }
    },
    getChoosedDeviceUrl(device) {
      const id = device.id
      const that = this
      this.currentPlayer.bLoading = true
      $.ajax({
        type: "GET",
        url: API_BASE_URL + "/if/getdeviceurl?appname=" + APP_NAME + '&deviceid=' + id +
          '&clientip=127.0.0.1&token=' + hex_md5(APP_NAME + id + '127.0.0.1' + SALT),
        success: function(result) {
          result = JSON.parse(result)
          if (result['hls']) {
            // that.currentPlayer.url = 'https://bs-hls.uvod.cn/live/223587_37562825_20211109193412_ab6941f560171863/playlist.m3u8'
            that.currentPlayer.url = result['hls']
            that.resetCloseTimer(that.currentPlayer)
            that.dialogTableVisible = false
          } else {
            that.$message.error('无效的设备播放地址')
          }
        },
        fail: function() {
          that.currentPlayer.bLoading = false
          that.$message.error('获取对应设备的播放地址失败')
        }
      });
    },
    updatePlayerLoading(player, event) {
      const val = event.detail[0]
      if (player) {
        player.bLoading = val
      }
    },
    handleM3u8Error(event) {
      const val = event.detail[0]
      if (val) {
        this.$message.error('该流无法播放，请重试！')
      }
    },
    handleDialogClose() {
      this.beforeDialog()
      this.currentPlayer = null
    },
    weiXinCode(url){
      //每次先清空二维码容器
      $("#qrcode").html("")
      $("#qrcode").qrcode({
        render: "canvas",            //设置渲染方式
        width: 200,                  //设置宽度,默认生成的二维码大小是 256×256
        height: 200,                 //设置高度
        typeNumber: -1,                 //计算模式
        background: "#ffffff",          //背景颜色
        correctLevel:0,
        text: url                     //设置二维码内容
      })
    },
    handleCustomEvent(player, event) {
      if (player && player.url) {
        this.dialogCodeVisible = true
        this.$nextTick(function() {
          this.weiXinCode(player.url)
        })
      }
    }
  },
  mounted() {
    if (isMobile) {
      this.playerLength = 1
    }
    this.setPlayerLength(this.playerLength)
  }
})
